package top.huxy.boot.model.dto;

import top.huxy.boot.exception.RequestAbortedException;
import top.huxy.boot.exception.RequestParamIllegalException;
import top.huxy.boot.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * @Classname Query
 * @Description Query
 * @Date 2021/9/26 17:23
 * @Created by huxy
 */
public class Query {
    private Map<String, String> rawQueryMap;
    private Map<String, Object> queryMap = new HashMap<>(2);

    public Query(HashMap<String, String> queryMap) {
        if (queryMap != null) {
            rawQueryMap = queryMap;
        } else {
            rawQueryMap = new HashMap<>(1);
        }
    }

    /**
     * 手动允许查询条件
     */
    public Query allowKey(String key, boolean required) {
        if (rawQueryMap == null) return this;
        if (rawQueryMap.containsKey(key)) {
            String s = rawQueryMap.get(key);
            if (StringUtils.isEmpty(s)) {
                if (required) {
                    throw new RequestParamIllegalException("param [" + key + "] is required");
                }
//                else {
//                    queryMap.put(key, s);
//                }
            } else {
                queryMap.put(key, s);
            }
        } else if (required) {
            throw new RequestParamIllegalException("param [" + key + "] is required");
        }
        return this;
    }

    public Query defaultValue(String key, Object defaultValue) {
        if (queryMap.containsKey(key)) return this;
        queryMap.put(key, defaultValue);
        return this;
    }

    /**
     * 复写查询条件
     */
    public Query replaceValue(String key, Function<String, Object> filter) {
        if (queryMap.containsKey(key)) {
            Object newValue;
            try {
                newValue = filter.apply(queryMap.get(key).toString());
            } catch (Exception e) {
                throw new RequestAbortedException(e.getMessage());
            }
            queryMap.replace(key, newValue);
        }
        return this;
    }

    /**
     * 获取查询条件
     *
     * @return
     */
    public Map<String, Object> getQueryMap() {
        return queryMap;
    }

    /**
     * 获取查询条件的值
     *
     * @return
     */
    public Object getQueryValue(String key) {
        return queryMap.get(key);
    }

    public boolean containsKey(String key) {
        return this.queryMap.containsKey(key);
    }
}
